﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TPA.DataAccess;
using System.Linq.Expressions;

namespace TVProgramAnalyst.TimeLine
{
    public partial class frmCombineWizard : Form
    {
        List<KeyPoint> _ProgramLog, _AdvertisementLog;//, _TimeLine;
        string _lasterror = "";
        public frmCombineWizard()
        {
            InitializeComponent();
        }

        //Load program log
        private void btnProg_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = global.Default.LastOpenLocation;//Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Excel files (*.xls;*.xlsx; *.xlsm)|*.xls;*.xlsx; *.xlsm|Excel 1997-2003 files (*.xls)|*.xls|Excel 2007-2010 files (*.xlsx)|*.xlsx";
            openFileDialog.Multiselect = false;
            
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                global.Default.LastOpenLocation = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
                ProgramLogReader pr = new ProgramLogReader();
                try
                {
                    _ProgramLog = pr.GetProgramLogKeyPoint(openFileDialog.FileName, "节目", false);
                    dataGridView1.DataSource = _ProgramLog;
                }
                catch (TPA.DataAccess.TPAException ex)
                {
                    MessageBox.Show(ex.Source);
                }
            }
        }

        //Load advertisement log
        private void btnAdv_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = global.Default.LastOpenLocation;// Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Excel files (*.xls;*.xlsx; *.xlsm)|*.xls;*.xlsx; *.xlsm|Excel 97-2003 files (*.xls)|*.xls|Excel 2007-2010 files (*.xlsx)|*.xlsx";
            openFileDialog.Multiselect = false;
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                global.Default.LastOpenLocation = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
                ProgramLogReader pr = new ProgramLogReader();
                try{
                    _AdvertisementLog = pr.GetAdvertisementLogKeyPoint(openFileDialog.FileName, "广告");
                    dataGridView2.DataSource = _AdvertisementLog;
                }
                catch (TPA.DataAccess.TPAException ex)
                {
                    MessageBox.Show(ex.Source);
                }
            }
        }

        //Combine keypoints to timeline
        private void button2_Click(object sender, EventArgs e)
        {
            TPAProgram._TimeLine = new List<KeyPoint>();
            progressBar1.Visible = true;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = _ProgramLog.Count + _AdvertisementLog.Count;

            for (int pindex = 0, aindex = 0; pindex < _ProgramLog.Count || aindex <_AdvertisementLog.Count;)
            {
                KeyPoint currentP = null,currentA=null;
                if (pindex < _ProgramLog.Count)
                {
                    currentP = _ProgramLog[pindex];
                }
                if (aindex < _AdvertisementLog.Count)
                {
                    currentA = _AdvertisementLog[aindex];
                }
                if (currentA != null && currentP != null)
                {
                    if (currentP.DateTimeIn < currentA.DateTimeIn)
                    {
                        //Add current program to timeline;
                        Helper.TimelineHelper.JoinKeyPoint(TPAProgram._TimeLine, currentP);
                        pindex++;
                        progressBar1.PerformStep();
                    }
                    else
                    {
                        //add current advertisement to timeline;
                        Helper.TimelineHelper.JoinKeyPoint(TPAProgram._TimeLine, currentA);
                        aindex++;
                        progressBar1.PerformStep();
                    }
                }
                else if (currentA != null)
                {
                    Helper.TimelineHelper.JoinKeyPoint(TPAProgram._TimeLine, currentA);
                    aindex++;
                    progressBar1.PerformStep();
                }
                else if (currentP != null)
                {
                    Helper.TimelineHelper.JoinKeyPoint(TPAProgram._TimeLine, currentP);
                    pindex++;
                    progressBar1.PerformStep();
                }
                
            }
            dataGridView3.DataSource = TPAProgram._TimeLine;
            progressBar1.Visible = false;
        }

        

        private void CombineWizard_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            _AdvertisementLog = new List<KeyPoint>();
            _ProgramLog = new List<KeyPoint>();
        }

        //Export to excel
        private void button1_Click(object sender, EventArgs e)
        {
            ProgramWriter writer = new ProgramWriter();
            MessageBox.Show(writer.WriteToExcel("anything", TPAProgram._TimeLine).ToString());
        }

        //Save time to database
        private void button3_Click(object sender, EventArgs e)
        {
            //SaveTimeline(_TimeLine);
            ParsePrograms(TPAProgram._TimeLine, out TPAProgram._ExistingPrograms, out TPAProgram._NewPrograms, out TPAProgram._ConflictPrograms
                ,out TPAProgram._NewChannels, out TPAProgram._ExistingChannels);
            //frmSaveToDatabase frm = new frmSaveToDatabase();
            //frm.ShowDialog(this);
        }

       private void ParsePrograms(List<KeyPoint> timeline, out List<TPA.DataAccess.Program> existingprograms, 
            out List<TPA.DataAccess.Program> newprograms, out List<TPA.DataAccess.Program> multiexistingprograms,
           out List<Channel> newchannels, out List<Channel> existingchannels)
        {
            existingprograms = new List<TPA.DataAccess.Program>();
            newprograms = new List<TPA.DataAccess.Program>();
            multiexistingprograms = new List<TPA.DataAccess.Program>();
            newchannels = new List<Channel>();
            existingchannels = new List<Channel>();

            pb4.Minimum = 0;
            pb4.Maximum = timeline.Count;
            //pb4.Visible = true;
            lblAnalysing.Visible = true;
            foreach (KeyPoint kp in timeline)
            {
                lblConflictedNumbers.Text = multiexistingprograms.Count.ToString();
                lblExistingNumber.Text = existingprograms.Count.ToString();
                lblNewNumber.Text = newprograms.Count.ToString();
                lblNewChannels.Text = newchannels.Count.ToString();
                lblExistingChannels.Text = existingchannels.Count.ToString();
                pb4.PerformStep();
                //Analyzing programs
                #region analyzing program
                IEnumerable<TPA.DataAccess.Program> programs_in_database = BLLFactory.ProgramBLL.GetPrograms(kp.Label);
                int count = programs_in_database.Count();
                if (count == 0)
                {
                    if (newprograms.Count(p => p.Name == kp.Label) == 0)
                    {
                        newprograms.Add(Helper.TimelineHelper.CreateProgramfromKeyPoint(kp));
                        //BLLFactory.ProgramBLL.Add(target);
                    }
                }
                else if (count == 1)
                {
                    if (existingprograms.Count(p => p.Name == kp.Label) == 0)
                    {
                        existingprograms.Add(programs_in_database.Single());
                    }
                }
                else
                {
                    if (multiexistingprograms.Count(p => p.Name == kp.Label) == 0)
                    {
                        multiexistingprograms.Add(Helper.TimelineHelper.CreateProgramfromKeyPoint(kp));
                    }
                }
                #endregion
                //Analyzing channels
                #region analyzing channels
                Channel c = BLLFactory.ChannelBLL.Get(kp.Channel);
                if (c != null)
                {
                    if (existingchannels.Count(ch => ch.Name == kp.Channel) == 0)
                        existingchannels.Add(c);
                }
                else
                {
                    if (newchannels.Count(ch => ch.Name == kp.Channel) == 0)
                        newchannels.Add(new Channel() { Name = kp.Channel });
                }
                #endregion

            }
            lblAnalysing.Visible = false;
        }
        
        

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            frmProgramResult frm = new frmProgramResult();
            frm.ShowDialog(this);
        }

        //save programs
        private void button4_Click(object sender, EventArgs e)
        {
            _lasterror = "";
            int saved = 0, cancelled = 0;
            pb4.Maximum = TPAProgram._NewPrograms.Count();
            pb4.Minimum = 0;
            pb4.Value = 0;
            lblSaving.Visible = true;
            foreach (Program p in TPAProgram._NewPrograms)
            {
                pb4.PerformStep();
                try
                {
                    BLLFactory.ProgramBLL.Add(p);
                    saved++;
                    lblNewSaved.Text = saved.ToString();
                }
                catch(Exception ex)
                {
                    cancelled++;
                    _lasterror=ex.Message;
                }
            }
            BLLFactory.ProgramBLL.SaveChanges();
            pb4.Maximum = TPAProgram._NewPrograms.Count();
            pb4.Minimum = 0;
            pb4.Value = 0;
            foreach (Channel c in TPAProgram._NewChannels)
            {
                pb4.PerformStep();
                try
                {
                    BLLFactory.ChannelBLL.Add(c);
                    saved++;
                    lblNewChannelsSaved.Text = saved.ToString();
                }
                catch (Exception ex)
                {
                    cancelled++;
                    _lasterror = ex.Message;
                }
            }
            BLLFactory.ChannelBLL.SaveChanges();
            _lasterror = saved + " saved; " + cancelled + " cancelled\n\r" + _lasterror;
            lblSaving.Visible = false;
        }

        private void llblViewSaveResult_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MessageBox.Show(_lasterror);
        }

        private void tabPage4_Click(object sender, EventArgs e)
        {

        }

        //save timeline
        private void btnSavetimeline_Click(object sender, EventArgs e)
        {
            //try{
                SaveTimeline(TPAProgram._TimeLine);
           // }
            //catch (Exception ex)
            //{
              //  MessageBox.Show(ex.Message);
            //}
        }

        //save time line
        //every program should be in database (existingprograms) now. if not exception will be throw out.
        private void SaveTimeline(List<KeyPoint> timeline)
        {
            //bool overwrite = false;
            pb4.Minimum = 0;
            pb4.Maximum = timeline.Count;
            pb4.Value = 0;
            foreach (KeyPoint kp in timeline)
            {
                pb4.PerformStep();
                Program program = TPAProgram._ExistingPrograms.Single(p => p.Name == kp.Label);
                if (program != null)
                {
                    TimelineSegment td = Helper.TimelineHelper.ConvertToTimelineSegment(kp, program);
                    if (BLLFactory.TimeLineBLL.IsExist(td))
                    {
                        BLLFactory.TimeLineBLL.Remove(td);
                    }
                    BLLFactory.TimeLineBLL.Add(td);
                    BLLFactory.TimeLineBLL.SaveChanges();
                }
                else
                {
                    throw new Exception() { Source = "missing program: " + kp.Label };
                }
            }
            
            lbltimelineitem.Text = timeline.Count.ToString();
        }

        private void tabPage5_Enter(object sender, EventArgs e)
        {
            comboBox1.DataSource = BLLFactory.TimeLineBLL.GetChannel();
            //BLLFactory.TimeLineBLL.RefreshView();
            //dataGridView4.DataSource = BLLFactory.TimeLineBLL.GetFinalList();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            //BLLFactory.TimeLineBLL.RefreshView();
            dataGridView4.DataSource = BLLFactory.TimeLineBLL.GetTimelineSegment(dateTimePicker1.Value,comboBox1.SelectedItem.ToString());
        }

        private void btnAnalyzingChannel_Click(object sender, EventArgs e)
        {

        }

        
    }
}
